package demo13;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

class TcpEchoServer{
        ServerSocket socket=null;

        public  TcpEchoServer(int port) throws IOException {
            socket=new ServerSocket(port);
        }

        /*public void start() throws IOException {
            System.out.println("服务器启动");
            while(true){
                Socket socketServer=socket.accept();
                processConnection(socketServer);
            }
        }
*/

    /*public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            Socket socketServer=socket.accept();
            Thread t=new Thread(()->{
                try {
                    processConnection(socketServer);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();

        }
    }*/

    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService service= Executors.newCachedThreadPool();
        while(true){
            Socket socketServer=socket.accept();
            service.submit(()->{
                try {
                    processConnection(socketServer);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });


        }
    }


        private void processConnection(Socket socketServer) throws IOException {
            System.out.printf("%s : %s \n",socketServer.getInetAddress(),socketServer.getPort());
            try(InputStream inputStream=socketServer.getInputStream();
            OutputStream outputStream=socketServer.getOutputStream()){
                while(true) {
                    PrintWriter writer = new PrintWriter(outputStream);
                    Scanner in = new Scanner(inputStream);
                    if (!in.hasNext()) {
                        System.out.println("下线");
                        break;
                    }
                    String request = in.next();
                    String respond = process(request);
                    writer.println(respond);
                    writer.flush();

                    System.out.printf("%s : %s , request : %s ,respond : %s  \n", socketServer.getInetAddress(), socketServer.getPort(),
                            request, respond);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                socketServer.close();
            }
        }

        public String process(String request) {
            return request;
        }


    public static void main(String[] args) throws IOException {
        TcpEchoServer server=new TcpEchoServer(9091);
        server.start();
    }
    }